package com.bootdo.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.app.common.annotion.IgnoreUserToken;
import com.bootdo.app.common.config.AuthConfig;
import com.bootdo.app.common.jwt.JWTInfo;
import com.bootdo.app.common.msg.Response;
import com.bootdo.app.common.utils.*;
import com.bootdo.app.dto.wx.Code2SessionDto;
import com.bootdo.app.dto.wx.UserDataDto;
import com.bootdo.app.dto.wx.UserDataDto2;
import com.bootdo.app.dto.wx.WxPayDo;
import com.bootdo.app.service.MiniProgramService;
import com.bootdo.app.service.UserGroupBuyService;
import com.bootdo.app.vo.miniprogram.LoginVo;
import com.bootdo.app.vo.miniprogram.WXUserVo;
import com.bootdo.common.utils.KswUtils;
import com.bootdo.system.domain.TbSvip;
import com.bootdo.system.domain.TbViporder;
import com.bootdo.system.domain.TbWeixinconfig;
import com.bootdo.system.domain.TbWxuser;
import com.bootdo.system.domain.Template;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.dto.GmspDto;
import com.bootdo.system.dto.ProductDto;
import com.bootdo.system.service.KswService;
import com.bootdo.system.service.OrderService;
import com.bootdo.system.service.ProductService;
import com.bootdo.system.service.UserService;
import com.bootdo.system.service.WalletService;
import com.bootdo.system.service.WxConfigService;
import com.bootdo.system.service.WxPayOrderService;
import com.bootdo.system.service.WxUserService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
 * @auther: 作者: Along
 * @description: 小程序控制类
 */
@RestController
@RequestMapping(value = "/app/mini_program")
public class WxLoginController {

	@Autowired
	private MiniProgramService miniProgramService;

	@Autowired
	private ProductService productService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private WxUserService wxUserService;

	@Autowired
	private WxConfigService wxConfigService;
	
	@Autowired
	private WalletService walletService;
	
	@Autowired
	private WxPayOrderService wxPayOrderService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private KswService kswService;
	
	@Autowired
	private UserGroupBuyService userGroupBuyService;

    @Autowired
    private AuthConfig authConfig;
	
	
	/**
	 * 小程序用户授权登陆 换取 jwt token
	 * 
	 * @param code2SessionDto
	 * @return
	 */
	@IgnoreUserToken
	@PostMapping(value = "/login")
	public Response login(@RequestBody Code2SessionDto code2SessionDto) {
		return Response.success(miniProgramService.login(code2SessionDto));
	}

	@IgnoreUserToken
	@GetMapping(value = "/testlogin")
	public Response logintet( String openid,  String appId){
        TbWeixinconfig wxConfig = wxConfigService.selectByAppId(appId);
        String sid = wxConfig.getAdminId().toString();
        TbWxuser wxUser = wxUserService.selectByWxOpenId(openid);
        WXUserVo userVo = null;

			userVo = new WXUserVo();
			BeanUtils.copyProperties(wxUser,userVo);
		String token = null;
		try {
			// 生成JWT中，包含用户的 id，sid,openId,sessionKey
			token = JWTUtil.generateToken(new JWTInfo(openid, wxUser.getId().toString(), "1", sid), authConfig.getPriKeyByte(), authConfig.getJwtExpire());
		} catch (Exception e) {

		}
		return Response.success(LoginVo.builder().id(wxUser.getId()).token(token).wxUserVo(userVo).build());
	}


	/**
	 * 解密小程序用户信息，并入库
	 */
	@PostMapping(value = "/decode_user_data")
	public Response decodeUserData(@RequestBody UserDataDto userDataDto) {
		return Response.success(miniProgramService.decodeUserData(userDataDto));
	}
	
	/**
	 * 解密小程序用户信息，并入库
	 */
	@PostMapping(value = "/decode_user_photo")
	public Response decodeUserData2(@RequestBody UserDataDto userDataDto) {
		return Response.success(miniProgramService.decodeUserData2(userDataDto));
	}

	/**
	 * 小程序会员卡
	 */
	@PostMapping(value = "/getProduct")
	public Response getProduct(@RequestBody  UserDataDto2 userDataDto) {
		Map<String, Object> map=new HashMap<String, Object>();
		TbWeixinconfig selectByAppId = wxConfigService.selectByAppId(userDataDto.getAppId());
		map.put("userId", selectByAppId.getAdminId());
		return Response.success(productService.list(map));
	}
	
	/**
	 * 小程序会员卡
	 */
	@PostMapping(value = "/getPath")
	public Response getPath(@RequestBody  UserDataDto2 userDataDto) {
		return Response.success(userDataDto.getGetPath());
	}

	/**
	 * 小程序我的订单
	 */
	@PostMapping(value = "/getOrder")
	public Response getOrder() {
		String openId = ContextHandlerUtil.getOpenId();
		return Response.success(orderService.listx2(openId));
	}
	
	/**
	 * 小程序我的钱包
	 */
	@PostMapping(value = "/getWdqb")
	public Response getWdqb() {
		Map<String, Object> map=new HashMap<String, Object>();
		TbWxuser userById = wxUserService.getUserById(ContextHandlerUtil.getOpenId());
		return Response.success(wxUserService.listJc2Log( userById.getId()));
	}
	
	/**
	 * 小程序基础信息
	 */
	@PostMapping(value = "/getAppData")
	public Response getAppData(@RequestBody  UserDataDto2 userDataDto) {
		return Response.success(wxConfigService.selectByAppId(userDataDto.getAppId()));
	}
	
	/**
	 * 小程序我的订单2带结算
	 */
	@PostMapping(value = "/getOrder2djs")
	public Response getOrder2djs() {
		String openId = ContextHandlerUtil.getOpenId();
		return Response.success(orderService.listx2djs(openId));
	}

	/**
	 * 小程序我的好友列表
	 */
	@PostMapping(value = "/getUserByOpenId")
	public Response getUserByOpenId() {
		String openId = ContextHandlerUtil.getOpenId();
		TbWxuser selectByWxOpenId = wxUserService.selectByWxOpenId(openId);
		if(selectByWxOpenId != null) {
			return Response.success(wxUserService.getUserByOpenId(selectByWxOpenId.getId().toString()));
		}
		return Response.fail();
	}

	/**
	 * 小程序个人中心
	 */
	@PostMapping(value = "/getUserById")
	public Response getUserById() {
		String openId = ContextHandlerUtil.getOpenId();
		return Response.success(wxUserService.getUserByOpenId2(openId));
	}
	
	/**
	 * 提现金额限制
	 */
	@PostMapping(value = "/getTxgz")
	public Response getTxgz() {
		return Response.success(walletService.getWall());
	}
	
	/**
	 * 
	 * @throws UnsupportedEncodingException 
	 */
	@PostMapping(value = "/getMthbUrl")
	public Response getMthbUrl() throws UnsupportedEncodingException {
		String openId = ContextHandlerUtil.getOpenId();
		TbWxuser userById = wxUserService.getUserById(openId);
		TbWeixinconfig selectByAppId = wxConfigService.selectByUserId(Integer.valueOf(userById.getSid()));
		Map<String,String> map=new HashMap<String,String>();
		String sid=userById.getSid()+"@"+openId;
		String mtsx = GetUrl(MtUrlUtils.mtsx,sid,selectByAppId.getProxykey());
		String mtwm = GetUrl(MtUrlUtils.mtwm,sid,selectByAppId.getProxykey());
		map.put("mtsx", mtsx);
		map.put("mtwm", mtwm);
		map.put("elmdehb", selectByAppId.getElemahongbao());
		map.put("elmhb", selectByAppId.getElemawaimai());
		map.put("elmgs", selectByAppId.getElemashangchao());
		return Response.success(map);
	}
	
	private String GetUrl(String mtsx,String sid,String appkey) {
		if(StringUtils.isNoneBlank(appkey)) {
			String res=mtsx+"?appkey="+appkey+":"+sid;
			String resCode = URLEncoder.encode(res);
			String aa=MtUrlUtils.head+"?key="+appkey+"&url="+resCode+"&sid="+sid;
			String encode = URLEncoder.encode(aa);
			String bb=MtUrlUtils.head2xcx+encode;
			return bb;
		}else {
			String res=mtsx+"?appkey="+MtUrlUtils.appkey+":"+sid;
			String resCode = URLEncoder.encode(res);
			String aa=MtUrlUtils.head+"?key="+MtUrlUtils.appkey+"&url="+resCode+"&sid="+sid;
			String encode = URLEncoder.encode(aa);
			String bb=MtUrlUtils.head2xcx+encode;
			return bb;
		}
		
	}

	@ResponseBody
	@RequestMapping(value = "/sendTemplateMessageMax", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	public Response sendTemplateMessagePro(@RequestBody String postData, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		JSONObject jsonObject = JSONObject.parseObject(postData);
		// 获取formID 发送消息模板必须参数
		String formId = jsonObject.getString("formId");
		// 获取接收方openID
		String openId = jsonObject.getString("openId");
		// 获取消息模板ID
		String templateId = jsonObject.getString("templateId");
		// 创建消息对象
		Template tem = new Template();
		// tem.setTemplateId("qBZ3BAC-Qs_LrcOqQ-NtVz7MM7bUKZ8ZubweSM0Wphg");
		// 赋值
		tem.setTemplateId(templateId);
		tem.setFormId(formId);
		tem.setTopColor("#00DD00");
		// tem.setToUser("oA5fM4rLOTbXX30h_0OzvO0chho4");
		tem.setToUser(openId);
		tem.setUrl("");
		// 创建消息内容
		List<TemplateParam> paras = new ArrayList<TemplateParam>();
		String keyword1 = jsonObject.getString("keyword1");
		if (keyword1 != null) {
			paras.add(new TemplateParam("keyword1", keyword1, "#0044BB"));
		}
		String keyword2 = jsonObject.getString("keyword2");
		if (keyword2 != null) {
			paras.add(new TemplateParam("keyword2", keyword2, "#0044BB"));
		}
		String keyword3 = jsonObject.getString("keyword3");
		if (keyword3 != null) {
			paras.add(new TemplateParam("keyword3", keyword3, "#0044BB"));
		}
		String keyword4 = jsonObject.getString("keyword4");
		if (keyword4 != null) {
			paras.add(new TemplateParam("keyword4", keyword4, "#0044BB"));
		}
		String keyword5 = jsonObject.getString("keyword5");
		if (keyword5 != null) {
			paras.add(new TemplateParam("keyword5", keyword5, "#0044BB"));
		}
		tem.setTemplateParamList(paras);
		// 获取微信token
		String appId = "wx27561fe9322705ce";
		TbWeixinconfig weChat = wxConfigService.selectByAppId(appId);
//      WeChat weChat = weChatService.selectByPrimaryKey(100);
		// 发送消息
		boolean result = WeChatConfig.sendTemplateMsg(tem, weChat.getServiceTemplate());
		return Response.success(result);

	}

	/**
	 * @param request
	 * @Description: 发起微信支付
	 */
	@ResponseBody
	@PostMapping(value = "/wxPay")
	public Response wxPay(@RequestBody WxPayDo postData, HttpServletRequest request) {
		try {
			// 获取手机号
			String phone = postData.getPhone();
			// 获取openid
			//新增 前端获取appid
			String appId = postData.getAppId();
			String openId = ContextHandlerUtil.getOpenId();
			// 获取价格,单位为分
			String totalFee = postData.getTotalFee();
			
			Double double2String = getDouble2String(totalFee);
			  if(double2String <= 0) {
				  totalFee="0.1";
			  }
			
			// 获取购买商品的名字
			String goodsName = postData.getGoodsName();
			
			String goodsId = postData.getGoodsId();
			TbWxuser userById = wxUserService.getUserById(openId);
			
			TbSvip byStoId = productService.getByStoId(Integer.valueOf(goodsId));
			if(byStoId != null) {
				Integer productid = byStoId.getProductid();
				String customer_id=KswUtils.customer_id;
				String key=KswUtils.ksw_key;
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhss");//设置日期格式
				String timestamp = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
				 TreeMap<String, String> treeMap = new TreeMap<String, String>();
				   treeMap.put("customer_id" , customer_id);
				   treeMap.put("timestamp" , timestamp);
				   ProductDto gmspDto = kswService.getSpxx(byStoId.getProductid(), key, treeMap);
				   if(gmspDto != null) {
					   int stock_state = gmspDto.getStock_state();
					   double price = gmspDto.getPrice();
					   if(stock_state == 2) {
						   return Response.fail("没有库存");
					   }else  if(stock_state == 1) {
						   UserDO userDO = userService.get(Long.valueOf(userById.getSid()));
							String balanceuc = userDO.getBalance();
							Double balanceu = getDouble2String(balanceuc);
							if(double2String < price) {
								Double res=price-double2String;
								if(res > balanceu) {
									 return Response.fail("商家余额不足");
								}
							}
					   }
				   }else {
					   return Response.fail("没有库存");
				   }
			}else{
				return Response.fail("商品查询不到");
			}
			boolean statusGroupBuy = userGroupBuyService.statusGroupBuy(goodsId);
			if(!statusGroupBuy) {
				return Response.fail("不能重复购买");
			}
			
			// 生成的随机字符串
			String nonce_str = WXPay.getRandomStringByLength(32);
			
//			TbWxuser userById = wxUserService.getUserById(openId);
			//插入微信用户订单表
//			TbUserWeixinPayOrder table = new TbUserWeixinPayOrder();
//			table.setPhone(phone);
//			table.setGoodsId(Long.valueOf(goodsId));
//			table.setUserId(Long.valueOf(userById.getId()));
//			table.setTotalFee(totalFee);
//			//待支付
//			table.setStatus(0);
//			
//			wxPayOrderService.insert2update(table);
			
			String pro = WXPay.getRandomStringByLength(32);
			TbViporder byOrdId =new TbViporder();
			byOrdId.setSid(userById.getSid() +"");
			byOrdId.setOid(pro);
			byOrdId.setOpenid(openId);
			byOrdId.setRechargeAccount(phone);
			byOrdId.setQuantity("1");
			byOrdId.setTitle("购买会员卡");
			byOrdId.setDirect(totalFee);
			byOrdId.setProductId(goodsId);
			byOrdId.setStatus(3);
			orderService.insert2updateSvip(byOrdId);
			
			
			// String pro = WXPay.getRandomStringByLength(32);
//			String pro = byOrdId.getId().toString();
			// 商品名称
			String body = goodsName;
			// 获取客户端的ip地址
			String spbill_create_ip = WXPay.getIpAddr(request);
			int totalFeeP=(int) (Double.parseDouble(totalFee) * 100);
			// 组装参数，用户生成统一下单接口的签名
			Map<String, String> packageParams = new HashMap<String, String>();
			packageParams.put("appid", appId);
			packageParams.put("mch_id", WXPay.WxPayConfig.mch_id);
			packageParams.put("nonce_str", nonce_str);
			packageParams.put("body", body);
			packageParams.put("out_trade_no", pro);// 商户订单号
			packageParams.put("total_fee", totalFeeP+"");// 支付金额，这边需要转成字符串类型，否则后面的签名会失败
			packageParams.put("spbill_create_ip", spbill_create_ip);
			packageParams.put("notify_url", WXPay.WxPayConfig.notify_url);// 支付成功后的回调地址
			packageParams.put("trade_type", WXPay.WxPayConfig.TRADETYPE);// 支付方式
			packageParams.put("openid", openId);
			String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
			// MD5运算生成签名，这里是第一次签名，用于调用统一下单接口
			String mysign = PayUtil.sign(prestr, WXPay.WxPayConfig.key, "utf-8").toUpperCase();

			// 拼接统一下单接口使用的xml数据，要将上一步生成的签名一起拼接进去
			String xml = "<xml>" + "<appid>" + appId + "</appid>" + "<body><![CDATA[" + body
					+ "]]></body>" + "<mch_id>" + WXPay.WxPayConfig.mch_id + "</mch_id>" + "<nonce_str>" + nonce_str
					+ "</nonce_str>" + "<notify_url>" + WXPay.WxPayConfig.notify_url + "</notify_url>" + "<openid>"
					+ openId + "</openid>" + "<out_trade_no>" + pro + "</out_trade_no>" + "<spbill_create_ip>"
					+ spbill_create_ip + "</spbill_create_ip>" + "<total_fee>" + totalFeeP + "</total_fee>"
					+ "<trade_type>" + WXPay.WxPayConfig.TRADETYPE + "</trade_type>" + "<sign>" + mysign + "</sign>"
					+ "</xml>";

			System.out.println(xml);
			System.out.println("----------");

			// 调用统一下单接口，并接受返回的结果
			String result = PayUtil.httpRequest(WXPay.WxPayConfig.pay_url, "POST", xml);

			System.out.println(result);

			// 将解析结果存储在HashMap中
			Map map = PayUtil.doXMLParse(result);

			String return_code = (String) map.get("return_code");// 返回状态码

			Map<String, Object> response = new HashMap<String, Object>();// 返回给小程序端需要的参数
			if (return_code == "SUCCESS" || return_code.equals(return_code)) {
				String prepay_id = (String) map.get("prepay_id");// 返回的预付单信息
				response.put("nonceStr", nonce_str);
				response.put("package", "prepay_id=" + prepay_id);
				Long timeStamp = System.currentTimeMillis() / 1000;
				response.put("timeStamp", timeStamp + "");// 这边要将返回的时间戳转化成字符串，不然小程序端调用wx.requestPayment方法会报签名错误
				// 拼接签名需要的参数
				String stringSignTemp = "appId=" + appId + "&nonceStr=" + nonce_str
						+ "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp;
				// 再次签名，这个签名用于小程序端调用wx.requesetPayment方法
				String paySign = PayUtil.sign(stringSignTemp, WXPay.WxPayConfig.key, "utf-8").toUpperCase();
				response.put("paySign", paySign);
			}

			response.put("appid", appId);

			return Response.success(response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @return
	 * @throws Exception
	 * @Description:微信支付
	 */
	@IgnoreUserToken
	@ResponseBody
	@RequestMapping(value = "/wxNotify", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	public void wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		br.close();
		// sb为微信返回的xml
		String notityXml = sb.toString();
		String resXml = "";
		System.out.println("接收到的报文：" + notityXml);
		Map map = PayUtil.doXMLParse(notityXml);
		String returnCode = (String) map.get("return_code");
		if ("SUCCESS".equals(returnCode)) {
			// 验证签名是否正确
			// 回调验签时需要去除sign和空值参数
			Map<String, String> validParams = PayUtil.paraFilter(map);
			// 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
			String validStr = PayUtil.createLinkString(validParams);
			// 拼装生成服务器端验证的签名
			String sign = PayUtil.sign(validStr, WXPay.WxPayConfig.key, "utf-8").toUpperCase();
			// 根据微信官网的介绍，此处不仅对回调的参数进行验签，还需要对返回的金额与系统订单的金额进行比对等
			if (sign.equals(map.get("sign"))) {
				/** 此处添加自己的业务逻辑代码start **/
				System.out.println("付款成功!!!!!!!!");
				// 获取openid
				String openid = (String) map.get("openid");
				// 获取订单号
				String order = (String) map.get("out_trade_no");

				// 根据订单号查询订单信息
//				TbUserWeixinPayOrder byId = wxPayOrderService.getById(Long.valueOf(order));
//				byId.setStatus(1);
				TbViporder byOrdId = orderService.getByOrdId(order);
				if(byOrdId == null) {
					System.out.println("付款失败~~~~~");
					resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
					BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
					out.write(resXml.getBytes());
					out.flush();
					out.close();
					return;
				}
				// 更改订单支付状态
//				byOrdId.setStatus(2);
				// 记录订单支付时间
//				byOrdId.setPaytime(DateUtil.formatLongDateTime(new Date()));
				// 支付方式
				// todo  明天此处改为微信支付订单表   更新操作 
//				orderService.insert2updateSvip(byOrdId);
				
				TbSvip byStoId = productService.getByStoId(Integer.valueOf(byOrdId.getProductId()));
				
				String customer_id=KswUtils.customer_id;
				String key=KswUtils.ksw_key;
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhss");//设置日期格式
				String timestamp = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
				 TreeMap<String, String> treeMap = new TreeMap<String, String>();
				   treeMap.put("customer_id" , customer_id);
				   treeMap.put("timestamp" , timestamp);
				GmspDto gmspDto = kswService.getGmspDto(byStoId.getProductid(), byOrdId.getRechargeAccount(), 1, key, treeMap);
				
				if(gmspDto != null) {
					String sid = byOrdId.getSid();
					String direct = byOrdId.getDirect();
					String doSidMoney = doSidMoney(sid,direct,byStoId.getProductid());
					byOrdId.setProfit(doSidMoney);
					byOrdId.setOid(gmspDto.getOrder_id());
					byOrdId.setStatus(2);
					// 记录订单支付时间
					byOrdId.setPaytime(DateUtil.formatLongDateTime(new Date()));
					// 支付方式
					// todo  明天此处改为微信支付订单表   更新操作 
					orderService.insert2updateSvip(byOrdId);
					//拼团结束
					userGroupBuyService.endGroupBuy(byOrdId.getProductId());
				}else {
					byOrdId.setStatus(4);
					// 支付方式
					// todo  明天此处改为微信支付订单表   更新操作 
					orderService.insert2updateSvip(byOrdId);
				}
				
				/** 此处添加自己的业务逻辑代码end **/
				
				//todo 写卡盟购买商品逻辑   根据订单编号查询手机号和订单记录
				
				// 通知微信服务器已经支付成功
				resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
						+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
			}
		} else {
			System.out.println("付款失败~~~~~");
			resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
					+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
		}
		System.out.println(resXml);
		System.out.println("微信支付回调数据结束");

		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
		out.write(resXml.getBytes());
		out.flush();
		out.close();
	}
	
	private String doSidMoney(String sid,String direct,int productid) {
		String customer_id=KswUtils.customer_id;
		String key=KswUtils.ksw_key;
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhss");//设置日期格式
		String timestamp = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
		TreeMap<String, String> treeMap = new TreeMap<String, String>();
	    treeMap.put("customer_id" , customer_id);
	    treeMap.put("timestamp" , timestamp);
	    ProductDto gmspDto = kswService.getSpxx(productid, key, treeMap);
	    if(gmspDto != null) {
	    	double price = gmspDto.getPrice();
	    	Double double2String = getDouble2String(direct);
	    	if(price > double2String) {
	    		Double res=price-double2String;
	    		UserDO userDO = userService.get(Long.valueOf(sid));
				String balanceuc = userDO.getBalance();
				Double balanceu = getDouble2String(balanceuc);
				userDO.setBalance((balanceu-res)+"");
				userService.update4(userDO);
				return "-"+res;
	    	}else if(double2String > price) {
	    		Double res=double2String-price;
	    		UserDO userDO = userService.get(Long.valueOf(sid));
				String balanceuc = userDO.getBalance();
				Double balanceu = getDouble2String(balanceuc);
				userDO.setBalance((balanceu+res)+"");
				userService.update4(userDO);
				return res+"";
	    	}
	    }
	    return null;
	}
	
	private Double getDouble2String(String num) {
		if(StringUtils.isNoneBlank(num)) {
			Double cny = Double.parseDouble(num);
			DecimalFormat df = new DecimalFormat("0.00"); 
			String CNY = df.format(cny);
			Double cny1 = Double.parseDouble(CNY);
			return cny1;
		}
		return 0.00;
	}
	

}
